#include "norder.h"
#include "ui_norder.h"

norder::norder(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::norder)
{
    ui->setupUi(this);
    Oo = "N";
    connect(ui->cancel, &QPushButton::clicked, this, &norder::cc);
    connect(ui->YesButton, &QPushButton::clicked, this, &norder::save);
    connect(ui->Oo, &QRadioButton::clicked, this, &norder::OOO);
}

norder::~norder()
{
    delete ui;
}

void norder::cc() {
    this->close();
}

void norder::save() {
    QString OrderID = ui->OrderID->text();
    QDateEdit *dateEdit = ui->ODate;
    QString ODate = dateEdit->date().toString("yyyy-MM-dd");
    QString ClientID = ui->ClientID->text();
    QString BookID = ui->BookID->text();
    QSpinBox * Count = ui->OCount;
    QString OCount = QString::number(Count->value());
    QString OMoney = ui->OMoney->text();
    QString OAdd = ui->OAdd->text();

    // 验证输入不为空
    if (BookID.isEmpty() || OrderID.isEmpty() || ODate.isEmpty() || ClientID.isEmpty() || OCount.isEmpty() || OMoney.isEmpty() || OAdd.isEmpty()) {
        QMessageBox::warning(this, "错误", "请填写所有必要信息(带有*)！");
        return;
    }

    // 执行SQL插入
    QSqlDatabase db = QSqlDatabase::database("qt_sql_default_connection");
    if (!db.isOpen()) {
        QMessageBox::warning(this, "错误", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    query.prepare("INSERT INTO OrderList (OrderID, ODate, ClientID, BookID, OCount, OMoney, OAdd, Oo) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(OrderID);
    query.addBindValue(ODate);
    query.addBindValue(ClientID);
    query.addBindValue(BookID);
    query.addBindValue(OCount);
    query.addBindValue(OMoney);
    query.addBindValue(OAdd);
    query.addBindValue(Oo);

    if (query.exec()) {
        QMessageBox::information(this, "成功", ":) 数据添加成功！");
        this->close();  // 关闭窗口
    } else {
        QMessageBox::critical(this, "错误",
                              QString(":( 数据添加失败，请检查"));
    }
}

void norder::OOO(bool checked) {
    Oo = checked ? "Y" : "N";
}
